package com.nurt.controller.user;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.SQLException;

import com.nurt.dto.ResultDto;
import com.nurt.entity.UserEntity;
import com.nurt.service.UserService;
import com.nurt.service.impl.UserServiceImpl;
import com.nurt.utils.ReturnCode;
import com.nurt.utils.ServletHelper;

@WebServlet(urlPatterns = "/users")
public class UpdateController extends HttpServlet {
    UserService userService;

    public void init() {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从请求中获取 JSON 数据
        UserEntity user = ServletHelper.getRequestBodyAsObject(req, UserEntity.class);

        try {
            // 调用 userService.updateUserInfo(user) 方法更新用户数据
            int updatedRows = userService.updateUserInfo(user);

            // 设置响应内容类型
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");

            // 根据更新的结果，设置响应的状态码和消息
            if (updatedRows > 0) {
                // 更新成功
                String rst = ResultDto.success(updatedRows);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                // 更新失败
                String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "更新失败。用户可能不存在。");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                resp.getWriter().write(rst);
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
}
